import { useState, useEffect } from 'react'
import { useSelector } from 'react-redux'
import { message, Form } from 'antd'
import to from 'await-to-js'
import dayjs from 'dayjs'

import { useAppDispatch } from '@/store'
import { applyData } from '@/api/apply'
import { applyAction, updataApplyData } from '@/store/modules/applyStore'
import { remindAcquireUpdate, updataRemindData } from '@/store/modules/remindStore'

import type { ResponseApplyList, RequestApplyData } from '@/api/apply/type'
import type { RequestRemindUpdate, ResponseRemindUpdate } from '@/api/remind/type'
import type { TypeApprover } from '@/api/login/type'
import type { RootState } from '@/store'
import type { RadioChangeEvent } from 'antd'
import _ from 'lodash'

//  页面数据
export const useApply = () => {
    const columns = [
        {
            title: '申请人',
            dataIndex: 'applicantname'
        },
        {
            title: '审批事由',
            dataIndex: 'reason'
        },
        {
            title: '时间',
            dataIndex: 'time'
        },
        {
            title: '备注',
            dataIndex: 'note'
        },
        {
            title: '审批人',
            dataIndex: 'approvername'
        },
        {
            title: '状态',
            dataIndex: 'state'
        }
    ]
    const approverStateList = [
        { label: '全部', value: '全部' },
        { label: '待审批', value: '待审批' },
        { label: '已通过', value: '已通过' },
        { label: '未通过', value: '未通过' }
    ]
    const defaultState = approverStateList[0].value

    const dispatch = useAppDispatch()
    // 检索关键字收集
    const [ keyword, setKeyword ] = useState('')
    //  请假事由options
    const [ selectedState, setSelectedState ] = useState(defaultState)
    // 列表数据
    const applyList = useSelector((state: RootState) => state.applyStore.applyList).filter(item => item.note.includes(keyword) && (item.state === selectedState || defaultState === selectedState))
    const userInfo = useSelector((state: RootState) => state.userStore.infos)

    //  关键词输入
    const keywordChange = (ev: React.ChangeEvent<HTMLInputElement>) => {
        setKeyword(ev.target.value)
    }

    // 数据状态切换
    const approverStateChange = ({ target: { value } }: RadioChangeEvent) => {
        setSelectedState(value)
    }

    //  用户点击检索
    const handelSearchBtn = () => {
        console.log('用户点击检索')
    }

    useEffect(() => {
        const getApplyData = async () => {
            const { payload } = await dispatch(applyAction({ applicantid: userInfo._id }))
            const { errcode, rets } = payload as ResponseApplyList
            if (errcode !== 0) return false
            dispatch(updataApplyData(rets))
        }

        if (_.isEmpty(applyList)) {
            getApplyData()
        }
    }, [ applyList, userInfo._id ])




    return {
        approverStateList,
        keyword,
        keywordChange,
        selectedState,
        approverStateChange,
        handelSearchBtn,
        applyList,
        columns
    }

}

// 弹窗
export const useModal = () => {
    const dispatch = useAppDispatch()
    const [ form ] = Form.useForm()
    const [ isModal, setIsModal ] = useState(false)
    const userInfo = useSelector((state: RootState) => state.userStore.infos)
    const remindInfo = useSelector((state: RootState) => state.remindStore.remindInfo)

    //  更新站内消息状态
    const postRemindAcquireUpdate = async (params:RequestRemindUpdate) => {
        const { payload } = await dispatch(remindAcquireUpdate(params))
        const { errcode, info } = payload as ResponseRemindUpdate
        if (errcode !== 0) return false
        dispatch(updataRemindData(info))
    }

    useEffect(() => {
        if (remindInfo.applicant) {
            const params = { userid: userInfo._id, applicant: false }
            postRemindAcquireUpdate(params).then()
        }

    }, [remindInfo.applicant, userInfo._id])


    const rules = {
        approvername: [ { required: true } ]
    }

    //  关闭弹窗
    const handleIsModal = () => {
        form.resetFields()
        setIsModal(!isModal)
    }

    //  添加审批-数据处理
    const onFinish = (value) => {
        value.time[0] = dayjs(value.time[0]).format('YYYY-MM-DD hh:mm:ss')
        value.time[1] = dayjs(value.time[1]).format('YYYY-MM-DD hh:mm:ss')
        const approverItem = userInfo.approver!.find(item => item.name === value.approvername) as TypeApprover
        const params = {
            ...value,
            applicantid: userInfo._id,
            applicantname: userInfo.name,
            approverid: approverItem._id
        } as RequestApplyData

        postApplyData(params)
    }

    // 添加审批-发送后端
    const postApplyData = async (params:RequestApplyData) => {

        const [ err, res ] = await to(applyData(params))
        err && console.error(err)

        const { errcode, errmsg } = res
        if (errcode === 0) {
            message.success('操作成功')
            handleIsModal()
            // 发送站内提示给审批人
            await postRemindAcquireUpdate({ userid: params.approverid, applicant: true })
        } else {
            return message.error(errmsg)
        }

    }


    return { isModal, handleIsModal, form, rules, approverList: userInfo.approver, onFinish }
}
